<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="序号" align="center" width="100">
        <template slot-scope="{$index}">
          <span>{{ $index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调查问卷" align="center">
        <template slot-scope="{row}">
          <span>{{ row.paperTitle }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="机构">-->
      <!--<template slot-scope="{row}">-->
      <!--<span>{{ row.orgId }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="{row}">
          <span>{{ row.testPaperStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="info" size="mini" @click="handleDetail(row,$index)">
            详情
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row,$index)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增/编辑考卷 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="400px">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" style="width: 100%;margin:0 auto">
        <el-row>
          <el-col>
            <el-form-item label="标题" prop="title">
              <el-input v-model="temp.paperTitle" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="机构" prop="type">
              <el-select v-model="temp.orgId" class="filter-item" placeholder="请选择" style="width:100%">
                <el-option
                  v-for="(item,index) in OrgList"
                  :key="index"
                  :label="item.orgName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="状态" prop="type">
              <el-select v-model="temp.testPaperStatus" class="filter-item" placeholder="请选择" style="width:100%">
                <el-option value="0" label="关闭">关闭</el-option>
                <el-option value="1" label="启用">启用</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
    <!-- <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" /> -->
    <el-drawer :title="testpaperTitle" :visible.sync="drawerFormVisible" size="60%" direction="ltr">
      <div class="testpaper-container">
        <div class="testpaper-header">
          <el-button type="primary" @click="handleObjectCreate()">
            新增
          </el-button>
        </div>
        <div class="testpaper-body">
          <draggable group="people" @start="drag=true" @end="drag=false">
            <el-card v-for="(item,index) in testPaperList" :key="index" class="box-card" style="margin-bottom:10px">
              <div slot="header" class="clearfix">
                <span>{{ '题干： '+item.content }}</span>
                <div style="float: right;">
                  <el-button style="padding: 5px;margin-right:5px" type="primary" @click="handleSubjectUpdate(item,index)">编辑</el-button>
                  <el-button style=" padding: 5px" type="danger" @click="handleSubjectDelete(item,index)">删除</el-button>
                </div>
              </div>
              <div v-for="o in 6" :key="o">
                <!-- 遍历选项 option1-option6 -->
                <p v-show="item[`${'option'+o}`]" class="text item">{{ '选项'+o+'： '+item[`${'option'+o}`] }}</p>
              </div>
            </el-card>
          </draggable>

        </div>
      </div>

    </el-drawer>
    <!-- 新增/编辑考题 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="innerdialogFormVisible" width="30%">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" style="width: 100%;margin:0 auto">
        <el-row>
          <el-col>
            <el-form-item label="题干" prop="title">
              <el-input v-model="subjectTemp.content" />
            </el-form-item>
          </el-col>
          <el-col v-for="o in 6" :key="o" style="margin-top:15px">
            <el-form-item :label="`${'选项'+o}`" prop="title">
              <el-input v-model="subjectTemp[`${'option'+o}`]" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="innerdialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createSubjectData():updateSubjectData()">
          保存
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>
<style>
  .el-card__body{
    padding:0 20px;
  }
  .el-drawer__body{
   height:100%
  }
  .testpaper-container{
    display: flex;
    flex-direction: column;
    height: 100%;
    padding:0 20px 20px;
    box-sizing: border-box
  }

  .testpaper-body{
    flex: 1;
    overflow-y:scroll;
  }

.testpaper-footer,.testpaper-header{
  width: 100%;
  padding:10px;
}
</style>
<script>

import { getallList, editApi, addApi, DeleteApi, getQuestionFromPaper, addQuestionIntoPaper } from '@/api/sysmanage'
import { getAllOrgList } from '@/api/public'
import waves from '@/directive/waves' // waves directive
import draggable from 'vuedraggable'
import { parseTime } from '@/utils'
// import Pagination from '@/components/Pagination' // secondary package based on el-pagination
export default {
  name: 'Opsurvey',
  components: { draggable },
  directives: { waves },
  data() {
    return {
      /* eslint-disable */
      value:'',
      innerdialogFormVisible:false,
      // getTypeList:[],
      OrgList:[],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        userType: '',
        jobNumber:'',
        orgId:''
      },
      temp:  {},
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      updateObj:{
        index:'',
        data:[]
      },
      dialogFormVisible:false,
      drawerFormVisible:false,
      testpaperTitle:'',
      paperId:'',
      testPaperList:[],//考题列表,
      subjectTemp:'',
      updateSubjectObj:'' 
    }
  },
  created() {
    getAllOrgList().then(res=>{
      this.OrgList=res.data
      console.log("TCL: created -> this.OrgLis", this.OrgLis)
    })
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getallList ().then(response => {
        this.list = response.data
        // this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      // this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {//重置修改模态框
      this.temp = {
        "orgId": '',
        "paperTitle": "",
        "testPaperStatus": ""
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        let num=Math.random()
      //  let _data= {
      //         "orgId": 0,
      //         "paperTitle": "测试试卷"+num,
      //         "testPaperStatus": "",
      //       }
        if (valid=true) {
          addApi(this.temp,'testPaper').then((res) => {
            const{code,message,data}=res
            if(code==='200'){
              this.$message({
                message: message,
                type: 'success',
              })
               this.dialogFormVisible = false
               this.list.unshift(data)
            }else{
              this.$message({
                message: message,
                type: 'warning',
              })
            }
          })
        }
      })
    },
    handleDetail(row,index){
      this.testpaperTitle=row.paperTitle
      const {id}=row
      this.paperId=id
      getQuestionFromPaper({id}).then(res=>{
        const {code,id,message,data}=res
        if(code==="200"){
            this.drawerFormVisible=true
            this.testPaperList=data?data:[]
        }else{
          this.$message({
            message: message,
            type: 'success',
          })
        }
      })

    },
    // -----------------------------------------------------
    resetObjectTemp(){
      // this.subjectTemp={
      //   "testPaperId":this.paperId,
      //   "content": "",
      //   "questionType": "0",
      //   "qustionStatus": "0",
      //   "option1": "",
      //   "option2": "",
      //   "option3": "",
      //   "option4": "",
      //   "option5": "",
      //   "option6": "",
      //   "departmentId": null,
      //   "answerCount": null
      // }
      this.subjectTemp={
        'id':0,
        "content": "",
        "option1": "",
        "option2": "",
        "option3": "",
        "option4": "",
        "option5": "",
        "option6": "",
        "questionType": "0",
        "qustionStatus": "0",
        "sortNumber": 0,
        "testPaperId": this.paperId,
      }
    },
    handleObjectCreate(){
      this.resetObjectTemp()
      this.dialogStatus = 'create'
      this.innerdialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createSubjectData(){
       addQuestionIntoPaper(this.subjectTemp,'question').then((res) => {
        const{code,message,data}=res
        console.log("TCL: createSubjectData -> data", data)
        if(code==='200'){
          this.$message({
            message: message,
            type: 'success',
          })
            this.dialogFormVisible = false
            this.testPaperList.unshift(data)
        }else{
          this.$message({
            message: message,
            type: 'warning',
          })
        }
      })
    },
    
    handleSubjectUpdate(row,index) {
       this.resetObjectTemp()
        this.subjectTemp = Object.assign({},row)
        this.updateSubjectObj={
          index:index,
          data:row
        }
      this.dialogStatus = 'update'
      this.innerdialogFormVisible = true
    },
    updateSubjectData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid=true) {
           const {index,data}=this.updateSubjectObj
          const tempData = Object.assign({}, this.subjectTemp)
          tempData.id=data.id
          editApi(tempData,'question').then((res) => {
            this.innerdialogFormVisible = false
            const {data,message}=res
            if(res.code==='200'){
               this.$message({
                message: res.message,
                type: 'success',
              })
              const row=tempData
              this.testPaperList.splice(index,1,row)
            }else{
               this.$message({
                message: res.message||'修改失败',
                type: 'error'
              })
            }
           
          })
        }
      })
    },
    handleSubjectDelete(row,index){
      console.log("TCL: handleSubjectDelete -> row", row)
      this.$confirm('此操作不可逆, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(res => {
         DeleteApi({id:row.id},'question').then(res=>{
             this.$message({
                message: res.message,
                type: 'success'
              })
              this.testPaperList.splice(index,1)
          }).catch(err=>{
             this.$message({
                message:err.message,
                type: 'error'
              })
          })
       
        // row.status = status
      })
    },
     // -----------------------------------------------------
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid=true) {
          const {index,data}=this.updateObj
          const tempData = Object.assign({}, this.temp)
          tempData.id=data.id
          editApi(tempData,'testPaper').then((res) => {
            this.dialogFormVisible = false
            if(res.code==='200'){
               this.$message({
                message: res.message,
                type: 'success',
              })
             
              const row=Object.assign(data, this.temp)
              console.log("TCL: updateData -> row", row)
              this.list.splice(index,1,row)
            }else{
               this.$message({
                message: res.message||'修改失败',
                type: 'error'
              })
            }
           
          })
        }
      })
    },
    handleUpdate(row,index) {
      this.temp = {
        "orgId": row.orgId,
        "paperTitle": row.paperTitle,
        "testPaperStatus": row.testPaperStatus
      }
      this.updateObj={
        index:index,
        data:row
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    handleDelete(row,index) {
      this.$confirm('此操作不可逆, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(res => {
         DeleteApi({id:row.id},'testPaper').then(res=>{
             this.$message({
                message: res.message,
                type: 'success'
              })
              this.list.splice(index,1)
          }).catch(err=>{
             this.$message({
                message:err.message,
                type: 'error'
              })
          })
       
        // row.status = status
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
   
  }
}
</script>
